const Class = require('../models/class');
const Student = require('../models/student');

// 班级控制器
const classController = {
  // 获取所有班级
  async getAllClasses(ctx) {
    try {
      const classes = await Class.find().populate('advisorId');
      ctx.body = {
        success: true,
        data: classes,
        count: classes.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取班级列表失败',
        error: error.message
      };
    }
  },

  // 根据ID获取班级
  async getClassById(ctx) {
    try {
      const cls = await Class.findById(ctx.params.id).populate('advisorId');
      if (!cls) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '班级不存在'
        };
        return;
      }
      ctx.body = {
        success: true,
        data: cls
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取班级信息失败',
        error: error.message
      };
    }
  },

  // 创建班级
  async createClass(ctx) {
    try {
      const { name, academy, stage, advisorId, subjects } = ctx.request.body;

      // 检查班级名称是否已存在
      const existingClass = await Class.findOne({ name });
      if (existingClass) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '班级名称已存在'
        };
        return;
      }

      // 创建班级
      const newClass = new Class({
        name,
        academy,
        stage,
        advisorId,
        subjects,
        studentCount: 0,
        status: 'active'
      });
      await newClass.save();

      // 如果指定了辅导员，更新班级信息
      if (advisorId) {
        await newClass.populate('advisorId');
      }

      ctx.status = 201;
      ctx.body = {
        success: true,
        message: '班级创建成功',
        data: newClass
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '创建班级失败',
        error: error.message
      };
    }
  },

  // 更新班级信息
  async updateClass(ctx) {
    try {
      const cls = await Class.findById(ctx.params.id);
      if (!cls) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '班级不存在'
        };
        return;
      }

      const updateData = ctx.request.body;
      // 更新班级信息
      Object.assign(cls, updateData);
      await cls.save();

      // 重新获取班级信息（包含关联数据）
      const updatedClass = await Class.findById(ctx.params.id).populate('advisorId');

      ctx.body = {
        success: true,
        message: '班级信息更新成功',
        data: updatedClass
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '更新班级信息失败',
        error: error.message
      };
    }
  },

  // 删除班级
  async deleteClass(ctx) {
    try {
      const cls = await Class.findById(ctx.params.id);
      if (!cls) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '班级不存在'
        };
        return;
      }

      // 检查班级是否有学生
      const studentCount = await Student.countDocuments({ classId: ctx.params.id });
      if (studentCount > 0) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '班级下还有学生，无法删除'
        };
        return;
      }

      // 删除班级
      await Class.findByIdAndDelete(ctx.params.id);

      ctx.body = {
        success: true,
        message: '班级删除成功'
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '删除班级失败',
        error: error.message
      };
    }
  },

  // 分页获取班级列表
  async getClassesPaginated(ctx) {
    try {
      const page = parseInt(ctx.query.page) || 1;
      const limit = parseInt(ctx.query.limit) || 10;
      const skip = (page - 1) * limit;

      // 构建查询条件
      const query = {};
      if (ctx.query.academy) {
        query.academy = ctx.query.academy;
      }
      if (ctx.query.stage) {
        query.stage = ctx.query.stage;
      }
      if (ctx.query.status) {
        query.status = ctx.query.status;
      }

      const classes = await Class.find(query)
        .skip(skip)
        .limit(limit)
        .populate('advisorId')
        .sort({ createdAt: -1 });

      const total = await Class.countDocuments(query);

      ctx.body = {
        success: true,
        data: classes,
        pagination: {
          total,
          page,
          limit,
          pages: Math.ceil(total / limit)
        }
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取分页班级列表失败',
        error: error.message
      };
    }
  },

  // 根据学院获取班级列表
  async getClassesByAcademy(ctx) {
    try {
      const classes = await Class.find({ academy: ctx.params.academy })
        .populate('advisorId');
      
      ctx.body = {
        success: true,
        data: classes,
        count: classes.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取学院班级列表失败',
        error: error.message
      };
    }
  },

  // 获取班级的学生列表
  async getClassStudents(ctx) {
    try {
      const cls = await Class.findById(ctx.params.id);
      if (!cls) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '班级不存在'
        };
        return;
      }

      const students = await Student.find({ classId: ctx.params.id })
        .populate('dormitoryId userId');
      
      ctx.body = {
        success: true,
        data: students,
        count: students.length
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取班级学生列表失败',
        error: error.message
      };
    }
  },

  // 获取班级的辅导员信息
  async getClassAdvisor(ctx) {
    try {
      const cls = await Class.findById(ctx.params.id).populate('advisorId');
      if (!cls) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '班级不存在'
        };
        return;
      }
      
      ctx.body = {
        success: true,
        data: cls.advisorId || null
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取班级辅导员信息失败',
        error: error.message
      };
    }
  }
};

module.exports = classController;